<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = [
        'name',
        'is_directory',
        'path',
        'level'
    ];

    protected $casts = [
        'is_directory' => 'boolean'
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function (Category $category) {
            if (is_null($category->parent_id)) {
                $category->level = 0; // 最顶级
                $category->path = "-";
            } else {
                $category->path = $category->parent->path . $category->parent_id . "-";
                $category->level = $category->parent->level + 1;
            }
        });
    }

    // 关联父栏目
    public function parent()
    {
        return $this->belongsTo(Category::class);
    }

    // 关联子栏目
    public function children()
    {
        return $this->hasMany(Category::class, "parent_id");
    }

    // 关联商品模型
    public function products()
    {
        return $this->hasMany(Product::class);
    }

    // 关联优惠券
    public function couponCodes()
    {
        return $this->morphMany(CouponCode::class, "coupon_codeable");
    }

    // 定义一个访问器获取所有祖先id
    public function getPathIdsAttribute()
    {
        return array_filter(explode('-', trim($this->path, '-')));
    }

    // 获取所有祖先对象
    public function getAncestorsAttribute()
    {
        return $this->query()
            ->whereIn('id', $this->path_ids)
            ->orderBy('level')
            ->get();
    }

    // 获取一个文字
    public function getFullNameAttribute()
    {
        return $this->ancestors->pluck('name')->push($this->name)->implode(' - ');
    }
}
